/**
 * Javascript file for form save and load handling.
 */

var FormSaveIDs = new Array();

function showSaveScreen(form_id) {
	FormSaveIDs = new Array();
	var xhrArgs = {
	        url: "ajax/ajax_forms.php?type=get_save_ids&form_id="+form_id,
	        handleAs: "json",
	        load: function(jsonData) {
	        	dojo.forEach(jsonData, function(SaveID) {
					if (SaveID !== null) {
						FormSaveIDs.push(SaveID.save_id);
					}
				});	        	
	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
	
	dijit.byId("SaveDialogContent").set("href","ajax/ajax_forms.php?type=save_UI&form_id="+form_id);
	dijit.byId("SaveDialog").set("title",TEXT_GENERAL_SAVE_FORM);
	dijit.byId("SaveDialog").show();
}

function showLoadScreen(form_id) {
	dijit.byId("SaveDialogContent").set("href","ajax/ajax_forms.php?type=load_UI&form_id="+form_id);
	dijit.byId("SaveDialog").set("title",TEXT_GENERAL_LOAD_FORM);
	dijit.byId("SaveDialog").show();
}

function validateSaveScreen(form_id) {
	dojo.byId("formsave_button").style.display = "none";
	dojo.byId("formsave_loading_icon").style.display = "";
	
	// validate name and return messages if required and make overwrite checkbox visible
	var new_save_id = dijit.byId("save_id").get("value");
	var overwrite   = dijit.byId("formsave_overwrite").get("checked");

	var id_exists = false;
	if (overwrite !== true) {
		for (var i=0; i<FormSaveIDs.length; i++) {
			if (FormSaveIDs[i] == new_save_id) {
				id_exists = true;
				break;
			}
		}
	}
	
	if (id_exists == false) {
		saveFormData(form_id, new_save_id);
	} else {
		// show overwrite checkbox
		dojo.byId("formsave_overwrite_content").style.display = "";
		dojo.byId("formsave_button").style.display = "";
		dojo.byId("formsave_loading_icon").style.display = "none";
	}

	
	
}


function saveFormData(form_id, save_id) {

	var i,j;
	var content = new Array();

	try {
		var form = dojo.byId(form_id);
		if (form == null) {
			alert("Wrong ID!"); // should never happen after release of Galaxytool 
			return false;
		}
		var inputs = form.getElementsByTagName("input");

		// Input fields (Radio, Checkbox, Hidden, Buttons, Passwd and normal input)
		for (i = 0; i < inputs.length; i++) {
			if (inputs[i].hasAttribute("wairole") == true) {
				// dojo control that causes trouble on loading but is not needed
				continue;
			}
			if (inputs[i].hasAttribute("readonly") == true) {
				// dojo dropdown icons have attributes with read only which cannot be set 
				continue;
			}
			if (inputs[i].getAttribute("type") == "button") {
				// no need to save button values
				continue;
			}
			
			if (inputs[i].getAttribute("type") == "radio") {
				if (inputs[i].checked == true) {
					content.push(new Array(inputs[i].name,inputs[i].value,"checked")); // do not store ID if available!
				}
			} else if (inputs[i].getAttribute("type") == "checkbox") {
				try {
					var dijit_checked = dijit.byId(inputs[i].id).get("checked");
				} catch(no_dijit_control) {
					var dijit_checked = false;
				}
				
				if (inputs[i].checked == true || inputs[i].hasAttribute("value") && dijit_checked == true) {
					content.push(new Array(new Array(inputs[i].id,inputs[i].name),"checked"));
				} else {
					content.push(new Array(new Array(inputs[i].id,inputs[i].name),""));
				}
			} else if (inputs[i].getAttribute("type") != "submit") {
				// hard coded deviations
				if (form_id == "userman1") {
					if (inputs[i].name != "id" && inputs[i].name != "username" && inputs[i].name != "ingameusername" && inputs[i].name != "email") {
						content.push(new Array(new Array(inputs[i].id,inputs[i].name),inputs[i].value));
					}
				} else {
					content.push(new Array(new Array(inputs[i].id,inputs[i].name),inputs[i].value));
				}
			}
		}

		// Text areas
		var textareas = form.getElementsByTagName("textarea");
		for (i = 0; i < textareas.length; i++) {
			content.push(new Array(new Array(inputs[i].id,inputs[i].name),textareas[i].value));
			//alert("Name: "+textareas[i].name+" Value: "+textareas[i].value);
		}

		// Selection boxes
		var selection = form.getElementsByTagName("select");
		var options;
		for (i = 0; i < selection.length; i++) {
			// check all options - which one is checked ?
			options = selection[i].getElementsByTagName("option");
			for (j = 0; j < options.length; j++) {
				if (options[j].selected == true) {
					content.push(new Array(selection[i].name,options[j].value));
					//alert("Name: "+selection[i].name+" Value: "+options[j].value);
				}

			}
		}
		
		// dojo selection boxes
		// table has class dijitSelect
		var selection = form.getElementsByTagName("table");
		var classes;
		for (i = 0; i < selection.length; i++) {
			// check all options - which one is checked ?
			classes = selection[i].getAttribute("class");
			if (classes != null && classes.indexOf("dijitSelect") > 0) {
				content.push(new Array(new Array(selection[i].id,""),dijit.byId(selection[i].id).get("value")));
			}
		}

		// save data
		saveData(form_id,save_id,content);

	} catch(e) {
		console.log("error:");
		console.log(e);
	}
	
	dojo.byId("formsave_overwrite_content").style.display = "none";
	dojo.byId("formsave_button").style.display = "";
	dojo.byId("formsave_loading_icon").style.display = "none";
	dijit.byId("SaveDialog").hide();

}


function loadFormData(form_id,save_id) {
	var obj;

	var xhrArgs = {
	        url: "ajax/ajax_forms.php?type=load_data&form_id="+form_id+"&save_id="+save_id,
	        handleAs: "json",
	        load: function(jsonData) {
	        	if (jsonData.messages != null) {
		        	// show messages
		        	showMessages(jsonData.messages);
	        	}
	        	
	        	if (jsonData.form_content.length == 0) {
	        		dijit.byId("SaveDialog").hide();
	        		return;
	        	} 
	        	content = jsonData.form_content;
	        	
	        	// reset form data
				for (var i = 0; i < content.length; ++i) {
					try {
						
						if (content[i][0] instanceof Array) {
							// new way to access data via ID or NAME (fallback)
							if (content[i][0][0] != "") {
								var tmp_obj = document.getElementById(content[i][0][0]);
							} else {
								var tmp_obj = document.getElementsByName(content[i][0][1]);
							}
						} else {
							// old stored data which is only stored with NAME
							var tmp_obj = document.getElementsByName(content[i][0]);						
						}
						
						if (tmp_obj.length == 1) {
							obj = tmp_obj[0];
						} else if ((tmp_obj instanceof Array || tmp_obj instanceof Object )&& tmp_obj.length > 1) {
							// radio buttons have the same name -> several hits
							for (k=0; k < tmp_obj.length; ++k) { // radio buttons have the same name
								obj = tmp_obj[k];

								if (obj.getAttribute("type") == "radio") {
									if (obj.value == content[i][1] && content[i][2] == "checked") {
										if ( obj.className.indexOf("dijit") > -1) {
											dijit.byId(content[i][0] + "" + obj.value).set("checked",true);											
											continue;
										} else {
											var checked_attr = document.createAttribute("checked");
											obj.setAttributeNode(checked_attr);
											obj.checked = true;
										}
									} else {
										obj.checked = false;
									}
								} else {
									console.log("unexpected else path");
								}
							}
							continue;
						} else {
							obj = tmp_obj;
						}

						// what kind of object do we have ?
						if (obj.nodeName == "SELECT") {
							// process all options of that node
							for (var j=0; j < obj.childNodes.length; ++j) {
								if (obj.childNodes[j].value == content[i][1]) {
									var selected_attr = document.createAttribute("selected");
									obj.childNodes[j].setAttributeNode(selected_attr);
									obj.childNodes[j].selected = true;
								} else {
									obj.childNodes[j].selected = false;
								}
							}
						}else if (obj.nodeName == "TABLE") {
							// dijit dropdowns
							dijit.byId(obj.id).set("value",content[i][1]);
						} else {
							if (obj.getAttribute("type") == "radio") {
								console.log("Radiobuttons must be handled via NAME but not ID");
							} else if (obj.getAttribute("type") == "checkbox") {
								if (content[i][1] == "checked") {
									//var checked_attr = document.createAttribute("checked");
									//obj.setAttributeNode(checked_attr);
									obj.checked = true;
									try {
										dijit.byId(obj.id).set("checked",true);
									} catch (no_dijit) {}
								} else {
									obj.checked = false;
									try {
										dijit.byId(obj.id).set("checked",false);
									} catch (no_dijit) {}
								}
							} else {
								obj.value = content[i][1];
							}
						}
					} catch(e) {
						//console.log("error: "+e);
						// element not found
					}
				}	        	
	        
				
				
				dijit.byId("SaveDialog").hide();
	        	
	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
}

function deleteFormData(form_id,save_id) {
	var xhrArgs = {
	        url: "ajax/ajax_forms.php?type=delete_data&form_id="+form_id+"&save_id="+save_id,
	        handleAs: "json",
	        load: function(jsonData) {
	        	// show messages
	        	showMessages(jsonData);
	        	
	        	dijit.byId("SaveDialog").hide();
	        	
	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);	
}

function saveData(form_id,save_id,content) {
	var xhrArgs = {
	        url: "ajax/ajax_forms.php?type=save_data&form_id="+form_id+"&save_id="+save_id,
	        handleAs: "json",
	        content: { form_content: dojo.toJson(content) },
	        load: function(jsonData) {
	        	// show messages
	        	showMessages(jsonData);
	        	
	        },
	        error: function(error) {
				console.log("Error:");
				console.log(error);
	        }
	}	
	dojo.xhrPost(xhrArgs);
}
